var MapDrag = function() {
	this.view = $("#minimap-view");
	this.drag = $("#minimap-drag");
	
	this.init();
};

MapDrag.prototype = {

	constructor: MapDrag,
	
	init: function() {
		var self = this,
			_view = this.view,
			_viewWidth = _view.width(),
			_viewHeight = _view.height(),
			_drag = this.drag,
			_dragWidth = _drag.width(),
			_dragHeight = _drag.height(),
			_viewOffset = _view.offset();
			
		this.img = _drag.find("img");
		this.maxW = _dragWidth - _viewWidth;
		this.maxH = _dragHeight - _viewHeight;
		this.viewRight = _viewOffset.left + _viewWidth;
		this.viewBottom = _viewOffset.top + _viewHeight;
		
		_drag.bind("mousedown", function(e){
			e.preventDefault();
			self.start(e);
		});
		
		self.load();
	},
	
	move: function(e) {
		var self = this,
			_drag = this.drag,
			moveX = self.dragX + (e.clientX - self.originX),
			moveY = self.dragY + (e.clientY - self.originY);
		
		(moveX > 0) ? moveX = 0 : "";
		(moveY > 0) ? moveY = 0 : "";
		(moveX < -self.maxW) ? moveX = -self.maxW : "";
		(moveY < -self.maxH) ? moveY = -self.maxH : "";
		
		_drag.css({
			"left": moveX,
			"top": moveY
		});
		
		self.load();
	},
	
	stop: function() {
		var self = this;
		self.drag.unbind("mousemove");
	},
	
	start: function(e) {
		var self = this,
			_drag = this.drag,
			_position = _drag.position();

		self.dragX = _position.left || 0;
		self.dragY = _position.top || 0;
		self.originX = e.clientX;
		self.originY = e.clientY;
		
		_drag.bind("mousemove", function(e) {
			e.preventDefault();
			self.move(e);
		});
		_drag.one("mouseup", function() {
			self.stop();
		});
	},
	
	load: function() {
		var self = this,
			_img = self.img;
			
		$.each(_img, function() {
			if (this.className !== "ready") {
				var _imgOffset = $(this).offset();
				if (_imgOffset.left < self.viewRight && _imgOffset.top < self.viewBottom) {
					$(this).attr("src", $(this).attr("loadsrc"));
					$(this).addClass("ready");
				}
			}
		});
	}
	
}

new MapDrag();